package me.weijing.common.xmpp;

import java.io.IOException;

import me.weijing.common.CommonApplication;

import org.apache.harmony.javax.security.auth.callback.Callback;
import org.apache.harmony.javax.security.auth.callback.CallbackHandler;
import org.apache.harmony.javax.security.auth.callback.NameCallback;
import org.apache.harmony.javax.security.auth.callback.PasswordCallback;
import org.apache.harmony.javax.security.auth.callback.UnsupportedCallbackException;
import org.apache.harmony.javax.security.sasl.RealmCallback;
import org.jivesoftware.smack.util.StringUtils;

import android.content.Context;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;

/**
 * An Authenticator which look for credentials stored in preferences.
 */
public class PreferenceAuthenticator implements CallbackHandler {

    private final SharedPreferences settings;

    /**
     * Create a PreferenceAuthenticator.
     * 
     * @param context
     *            the Android context.
     */
    public PreferenceAuthenticator(final Context context) {
        settings = PreferenceManager.getDefaultSharedPreferences(context);
    }

    @Override
    public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
        String tmpJid = settings.getString(CommonApplication.ACCOUNT_USERNAME_KEY, "").trim();
        String service = StringUtils.parseServer(tmpJid);

        for (int i = 0; i < callbacks.length; i++) {
            if (callbacks[i] instanceof NameCallback) {
                String authenticationId = StringUtils.parseName(tmpJid);
                if (settings.getBoolean(CommonApplication.FULL_JID_LOGIN_KEY, false) || "gmail.com".equals(service) || "googlemail.com".equals(service)) {
                    authenticationId = tmpJid;
                }
                NameCallback ncb = (NameCallback) callbacks[i];
                ncb.setName(authenticationId);
            } else if (callbacks[i] instanceof PasswordCallback) {
                PasswordCallback pcb = (PasswordCallback) callbacks[i];
                // skip if password is asked for PKCS11 (SSL keystore)
                String prompt = pcb.getPrompt();
                if (prompt != null && prompt.startsWith("PKCS11 Password:"))
                    continue;
                String password = settings.getString(CommonApplication.ACCOUNT_PASSWORD_KEY, "");
                pcb.setPassword(password.toCharArray());
            } else if (callbacks[i] instanceof RealmCallback) {
                RealmCallback rcb = (RealmCallback) callbacks[i];
                rcb.setText(service);
            } else {
                throw new UnsupportedCallbackException(callbacks[i]);
            }
        }
    }

}
